<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model.trim="query.query.materialName" clearable placeholder="请输入货品名称" @keyup.enter.native="search" />
      <el-select v-model="query.query.warehouseId" clearable placeholder="请选择仓库">
        <el-option v-for="item in warehouseList" :key="item.id" :label="item.warehouseName" :value="item.id" />
      </el-select>
      <el-date-picker v-model="q_p_formDate1" format="yyyy-MM-dd" value-format="yyyy-MM-dd" type="daterange"
        range-separator="-" start-placeholder="起始日期" end-placeholder="终止日期" @change="q_p_selectTimecreate" />
      <el-button type="primary" icon="el-icon-search" @click="search">
        {{ $t('table.search') }}
      </el-button>
    </div>
    <el-table :data="tableData" row-key="id" highlight-current-row border
      :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }">
      <el-table-column prop="materialNo" label="货品编码" sortable />
      <el-table-column label="货品名称" prop="materialName" sortable />
      <el-table-column label="单位" prop="unit" sortable />
      <el-table-column prop="model" label="规格" align="center" sortable />
      <el-table-column prop="warehouseName" label="仓库" align="center" sortable />
      <!-- <el-table-column prop="stockNum" label="当前库存" align="center" /> -->
      <el-table-column prop="safeStock" label="安全库存" align="center" />
      <el-table-column prop="startStoreNum" label="期初结存数量" align="center" sortable />
      <el-table-column prop="currentInStoreNum" label="本期收入数量" align="center" sortable />
      <el-table-column prop="currentOutStoreNum" label="本期发出数量" align="center" sortable />
      <el-table-column prop="endStoreNum" label="期末结存数量" align="center" sortable />
      <!-- <el-table-column label="创建日期" prop="createTime" sortable width="180">
        <template slot-scope="{ row }">
          <span>{{ row.createTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
</el-table-column> -->
      <!-- <el-table-column :label="$t('table.actions')" align="center">
        <template slot-scope="{ row, $index }">
          <el-button type="primary" size="mini" @click="handleDetail(row, $index)">
            明细
          </el-button>
        </template>
      </el-table-column> -->
    </el-table>
    <el-pagination style="margin-top: 20px;" :current-page="query.pageIndex" :page-sizes="[5, 10, 20, 50]"
      :page-size="query.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"
      @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    <el-dialog title="明细" :visible.sync="dialogVisible" :close-on-click-modal="false">
      <el-table :data="gridData" highlight-current-row border :header-cell-style="{ 'text-align': 'center' }"
        :cell-style="{ 'text-align': 'center' }">
        <el-table-column prop="inoutStoreNo" label="出/入库单号" width="160px" />
        <el-table-column label="出/入库" prop="inOut">
          <template slot-scope="{row}">
            {{ row.inOut == 1 ? '入库' : '出库' }}
          </template>
        </el-table-column>
        <el-table-column prop="changeType" label="变动类型">
          <template slot-scope="{row}">
            {{ getApplyType(row.changeType) }}
          </template>
        </el-table-column>
        <el-table-column prop="changeNum" label="变动数量" />
        <el-table-column label="变动时间" prop="changeTime" width="160px">
          <template slot-scope="{ row }">
            <span>{{ row.changeTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" label="状态">
          <template slot-scope="{ row }">
            <span>{{ row.state == 1 ? '已确认' : '未确认' }}</span>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination style="margin-top: 20px;" :current-page="query.pageIndex" :page-sizes="[5, 10, 20, 50]"
        :page-size="detailQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="detailTotal"
        @size-change="detailHandleSizeChange" @current-change="detailHandleCurrentChange" />
    </el-dialog>
  </div>
</template>
<script>

import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import { stokcPageList, warehousePageList, wmsStockDetail } from '@/api/qmsQualityManagement'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
const project = {
  id: 0
}

export default {
  name: 'Project',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      dialogVisible: false,
      gridData: [],
      fileNamedan: '',
      q_p_formDate1: [],
      fileName1: '',
      warehouseList: [],
      query: {
        pageIndex: 1,
        pageSize: 10,
        query: {
          beginDate: "",
          endDate: "",
          warehouseId: ""
        }
      },
      total: 0,
      project: Object.assign({}, project),
      tableData: [],
      filename: '客诉台账',
      fileNameId: '',
      detailQuery: {
        pageIndex: 1,
        pageSize: 10,
        query: {
          materialId: '',
          warehouseId: ""
        }
      },
      gridData: []
    }
  },
  computed: {
    tableData12() {
      return this.tableData.filter((item) => { return item.status == 2 || item.status == 3 || item.status == 4 || item.status == 6 })
    }
  },
  mounted() {
    this.getday()
    this.getWarehousePageList()
  },
  methods: {
    getApplyType(val) {
      if (val == 1) {
        return "销售出库";
      } else if (val == 2) {
        return "采购入库";
      } else if (val == 3) {
        return "退货入库";
      } else if (val == 4) {
        return "调拨入库";
      } else if (val == 5) {
        return "调拨出库";
      }
    },
    detailHandleSizeChange(size) {
      this.detailQuery.pageSize = size
      this.getWmsStockDetail()
    },
    detailHandleCurrentChange(currentPage) {
      this.detailQuery.pageIndex = currentPage
      this.getWmsStockDetail()
    },
    async handleDetail(row) {
      const { query } = this.detailQuery
      query.materialId = row.materialId
      query.warehouseId = row.warehouseId
      await this.getWmsStockDetail()
      this.dialogVisible = true
    },
    async getWmsStockDetail() {
      const { records, total } = await wmsStockDetail(this.detailQuery)
      this.gridData = records
      this.detailTotal = total
    },
    downLoad2(id) {
      download(id).then(res => {
        const content = res
        const blob = new Blob([content]) // 构造一个blob对象来处理数据
        const fileName = this.fileNamedan // 导出文件名
        if ('download' in document.createElement('a')) { // 支持a标签download的浏览器
          const link = document.createElement('a') // 创建a标签
          link.download = fileName // a标签添加属性
          link.style.display = 'none'
          link.href = URL.createObjectURL(blob)
          document.body.appendChild(link)
          link.click() // 执行下载
          URL.revokeObjectURL(link.href) // 释放url
          document.body.removeChild(link) // 释放标签
        } else { // 其他浏览器
          navigator.msSaveBlob(blob, fileName)
        }
      })
    },
    getday() {
      const date = new Date()
      const lastDays = new Date(date.setMonth(date.getMonth()+1, 0)).getDate()
      const yy = date.getFullYear();
      const mm = date.getMonth() + 1;
      const currDate = new Date(yy,mm-1,lastDays).toLocaleDateString().split('/').join('-')// 2020/11/6
      const pdStr = new Date(yy, mm - 1, 1).toLocaleDateString().split('/').join('-');
      this.query.query.beginDate = pdStr
      this.query.query.endDate = currDate
      this.q_p_formDate1 = [pdStr, currDate]
      this.getInfo()
    },
    q_p_selectTimecreate(val) {
      const { query } = this.query
      if (val) {
        query.beginDate = val[0]
        query.endDate = val[1]
      } else {
        query.beginDate = query.endDate = ''
      }
    },
    downLoad() {
      download(this.fileNameId).then(res => {
        console.log(res)
        const content = res
        const blob = new Blob([content]) // 构造一个blob对象来处理数据
        const fileName = this.fileName1 // 导出文件名
        if ('download' in document.createElement('a')) { // 支持a标签download的浏览器
          const link = document.createElement('a') // 创建a标签
          link.download = fileName // a标签添加属性
          link.style.display = 'none'
          link.href = URL.createObjectURL(blob)
          document.body.appendChild(link)
          link.click() // 执行下载
          URL.revokeObjectURL(link.href) // 释放url
          document.body.removeChild(link) // 释放标签
        } else { // 其他浏览器
          navigator.msSaveBlob(blob, fileName)
        }
      })
    },
    handleExceed(files, fileList) {
      // console.log(files, fileList);
      this.$message.warning(`一次最多上传5个文件，请分批次上传! `)
    },
    beforeUpload(file) {
      // this.formData.fileName = file.name
      if (this.project.id == 0) {
        this.$message.warning('请先保存客诉台账再上传不良描述附件')
        return false
      }
      const size10M = file.size / 1024 / 1024 <= 20
      if (!size10M) {
        this.$message.warning('上传文件大小不能超过20MB!')
        return false
      }
      var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
      const extension = ['txt', 'doc', 'docx', 'xls', 'xlsx', 'pdf', 'jpg', 'png', 'jpeg']
      if (extension.indexOf(testmsg) == -1) {
        this.$message({
          message: '上传文件只能是.TXT、.DOC、.DOCX、.XLS、.XLSX、.PDF、.JPG、.PNG、.JPEG格式!',
          type: 'warning'
        })
        return false
      }
    },
    async uploadActionUrl1(item) {
      const fileObj = item.file
      const form = new FormData()
      form.append('file', fileObj)

      const loading = this.$loading({
        lock: true,
        text: '文件上传中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      await uploadFile(this.project.id, 2, form).then((response) => {
        if (response.isSuccess) {
          this.$message.success('文件：' + fileObj.name + '上传成功')
          loading.close()
          this.$refs.upload1.clearFiles()
        } else {
          this.$message.error('文件：' + fileObj.name + '上传失败')
        }
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['NCR No.', '客户', '创建人', '状态', '产品', '图号', '不良描述', '不良数量', '不良批次', '创建日期', '处理方式', '处置', '问题来源', '客户抱怨', '报废费用', '返工费用', '超额运费', '合计', '供应商索赔费用']
        const filterVal = ['ncrNumber', 'customer', 'createUserName', 'status', 'product', 'pictureNumber', 'harmfulDescribe', 'harmfulNumber', 'batchNumber', 'createTime', 'handleWay', 'solution', 'reason', 'blame', 'scrapCost', 'reworkCost', 'excessCost', 'total', 'supplierClaimExpense']
        const tableData = this.tableData12
        const data = this.formatJson(filterVal, tableData)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: this.filename,
          autoWidth: this.autoWidth,
          bookType: this.bookType
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        console.log(j)
        if (j === 'createTime') {
          return parseTime(v[j])
        } else if (j === 'blame') {
          console.log(v)
          return this.blameval(v)
        } else if (j === 'status') {
          return this.stateList(v)
        }
        // else if(j === 'dan'){
        //    return this.danlist(v)
        // }

        else {
          return v[j]
        }
      }))
    },
    blameval(data) {
      if (data.blame == '1') {
        return '正式'
      } else if (data.blame == '2') {
        return '非正式'
      }
    },
    stateList(data) {
      if (data.status == '1') {
        return '待提交'
      } else if (data.status == '6') {
        return '完成'
      } else if (data.status == '2') {
        return '创建'
      } else if (data.status == '3') {
        return '费用确认'
      } else if (data.status == '4') {
        return '完成'
      }
    },

    handleShowProjectFile(row) {
      download(row.id).then(res => {
        const content = res
        const blob = new Blob([content]) // 构造一个blob对象来处理数据
        const fileName = row.fileName // 导出文件名
        if ('download' in document.createElement('a')) { // 支持a标签download的浏览器
          const link = document.createElement('a') // 创建a标签
          link.download = fileName // a标签添加属性
          link.style.display = 'none'
          link.href = URL.createObjectURL(blob)
          document.body.appendChild(link)
          link.click() // 执行下载
          URL.revokeObjectURL(link.href) // 释放url
          document.body.removeChild(link) // 释放标签
        } else { // 其他浏览器
          navigator.msSaveBlob(blob, fileName)
        }
      })
    },
    handleCurrentChange(currentPage) {
      this.query.pageIndex = currentPage
      this.getInfo()
    },
    canclebtn(ruleForm) {
      this.dialogVisible = false
    },
    handleSizeChange(size) {
      this.query.pageSize = size
      this.getInfo()
    },
    // handleDetail(row, $index) {
    //   this.gridData = [row]
    //   this.dialogVisible = true
    // },
    search() {
      this.query.pageIndex = 1
      this.getInfo()
    },
    getInfo() {
      stokcPageList(this.query).then((res) => {
        const { records, total } = res
        this.tableData = records
        this.total = total
      })
    },
    getWarehousePageList() {
      warehousePageList({
        query: { state: "1" }
      }).then(res => {
        this.warehouseList = res
      })
    }
  }
}
</script>

<style scoped>
.addinput /deep/ .el-input__inner {
  border: none;
  background: #f5f7fa;

}

.addinput /deep/ .el-textarea__inner {
  border: none;
  background: #f5f7fa;

}

.downfile {
  text-decoration: underline;
  color: blue;
}
</style>
